import dash,os
from dash import html, dcc, dash_table
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np
from datetime import datetime, date
from flask import session # 确保导入 session
from models import Organization, Department, Product as Equipment # 确保导入 Equipment
from sqlalchemy import func # 确保导入 func
from models import db, RepairRecord

# 创建顶部标题栏
def create_header_panel():
    from flask import session
    
    # 获取当前用户的机构信息
    org_code = session.get('current_org_code', session.get('user_org_code', ''))
    org_name = "上海市黄浦区社区卫生服务中心"  # 默认名称
    org_full_name = org_name  # 初始化变量
    
    if org_code and org_code != 'hpqwjw':
        from models import Organization
        org = Organization.query.filter_by(org_code=org_code).first()
        if org:
            org_full_name = org.org_name or org_name
    
    return html.Div([
        html.Div([
            html.H1(
                org_full_name,
                style={
                    "color": "white",
                    "fontSize": "28px",
                    "fontWeight": "bold",
                    "margin": "0",
                    "textAlign": "center",
                    "flex": "1"
                }
            ),
            html.Div([
                dcc.DatePickerRange(
                    id='branch-date-picker-range',
                    start_date=date(datetime.now().year, 1, 1),
                    end_date=date.today(),
                    display_format='YYYY-MM-DD',
                    style={'marginRight': '10px'}
                ),
                html.Button(
                    "关闭",
                    id="close-button",
                    style={
                        "backgroundColor": "#1890ff",
                        "color": "white",
                        "border": "none",
                        "padding": "8px 16px",
                        "borderRadius": "4px",
                        "cursor": "pointer"
                    }
                )
            ], style={
                "display": "flex",
                "alignItems": "center"
            })
        ], style={
            "display": "flex",
            "justifyContent": "space-between",
            "alignItems": "center",
            "padding": "15px 30px"
        })
    ], style={
        "backgroundColor": "#222",
        "height": "80px",
        "width": "100%"
    })

# 创建资产分布面板（上排第1列）
def create_asset_distribution_panel():
    # 将获取科室选项的逻辑移到函数内部
    department_options = [{'label': '全部科室', 'value': 'all'}] # 默认选项
    org_code = session.get('current_org_code', session.get('user_org_code'))
    
    # 从Excel文件读取数据
    asset_labels = []
    asset_values = []
    total_amount = "0.00万元"
    total_count = "0台"
    
    # 定义一组颜色，如果科室数量超过颜色数量，可以考虑循环使用或生成随机颜色
    colors = ['#00d4ff', '#00ff88', '#ffaa00', '#ff6b6b', '#a78bfa', '#f0e442', '#009e73', '#d55e00', '#cc79a7', '#56b4e9'] 
    
    if org_code:
        # 根据 org_code 找到对应的 organization.short_name_c
        organization = Organization.query.filter_by(org_code=org_code).first()
        
        if organization and organization.short_name_c:
            # 根据机构简称确定要读取的Excel文件
            org_name = organization.short_name_c
            excel_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "statistic","xlsx3",f"{org_name}_科室和金额区间统计.xlsx"))
            # print(f"读取的Excel文件路径: {excel_path}")
            
            try:
                # 读取Excel文件中的"科室和金额区间统计"sheet
                df = pd.read_excel(excel_path, sheet_name="科室和金额区间统计")
                
                # 假设Excel中有科室和数量的列
                # 根据实际Excel结构调整列名
                dept_column = "科室" # 根据实际Excel列名调整
                count_column = "设备合计台数" # 修改为实际的设备总数列名
                
                # 获取科室和数量数据
                for _, row in df.iterrows():
                    dept = row[dept_column]
                    count = row[count_column]
                    # 过滤掉合计行，只显示具体科室的数据
                    if pd.notna(dept) and pd.notna(count) and count > 0 and dept != '合计':
                        asset_labels.append(dept)
                        asset_values.append(count)
                        
                # 获取总金额和总数量
                # 假设Excel中有这些信息，根据实际情况调整
                if "总金额(万元)" in df.columns:
                    total_amount = f"{df['总金额(万元)'].sum():.2f}万元"
                if "总数量" in df.columns:
                    total_count = f"{int(df['总数量'].sum())}台"
                    
                # 获取科室选项
                departments = list(set(df[dept_column].dropna()))
                department_options = [{'label': '全部科室', 'value': 'all'}]
                department_options.extend([{'label': dept, 'value': dept} for dept in departments if dept])
                
            except Exception as e:
                print(f"读取Excel文件出错: {e}")
                asset_labels = ['读取数据出错']
                asset_values = [1]
                colors = ['#D3D3D3']
        else:
            # 如果找不到组织信息，可以显示空数据或默认数据
            asset_labels = ['暂无数据']
            asset_values = [1]
            colors = ['#D3D3D3'] # 灰色
    else:
        # 如果没有 org_code，也显示空数据或默认数据
        asset_labels = ['请选择机构']
        asset_values = [1]
        colors = ['#D3D3D3'] # 灰色

    # 如果数据为空，提供一个占位符
    if not asset_labels:
        asset_labels = ['无资产数据']
        asset_values = [1]
        colors = ['#D3D3D3']

    asset_pie_chart = go.Figure(
        data=[go.Pie(
            labels=asset_labels,
            values=asset_values,
            hole=.6, # 设置饼图的中心孔大小，创建环形图效果
            marker=dict(colors=colors[:len(asset_labels)]), # 使用定义的颜色
            textinfo='none', # 不显示任何文字信息
            insidetextorientation='radial', # 标签方向
            hoverinfo='label+percent+value', # 悬停时显示信息
            sort=True, # 按数据大小排序
            direction='clockwise' # 顺时针排列
        )]
    )
    
    asset_pie_chart.update_layout(
        paper_bgcolor='rgba(0,0,0,0)',
        plot_bgcolor='rgba(0,0,0,0)',
        font=dict(color='white'),
        margin=dict(t=20, b=20, l=20, r=20),
        height=200,  # 适当调整图表高度
        showlegend=False
    )
    
    return html.Div([
        # 第一行：标题
        html.H3(" | 资产分布", style={
            "color": "white",
            "fontSize": "18px",
            "marginBottom": "15px",
            "textAlign": "left",  # 修改为 left
            #"paddingTop": "1px" # 增加上边距
        }),
        # 第二行：左侧选择框，右侧总金额
        dbc.Row([
            # 左侧选择框
            dbc.Col([
                dcc.Dropdown(
                    id='branch-amount-filter',
                    options=[
                       {'label': '全部区间', 'value': 'all'},
                        {'label': '0-1万', 'value': '0-1万'},
                        {'label': '1-5万', 'value': '1-5万'},
                        {'label': '5-10万', 'value': '5-10万'},
                        {'label': '10-50万', 'value': '10-50万'},
                        {'label': '50-100万', 'value': '50-100万'},
                        {'label': '100万以上', 'value': '100万以上'}
                    ],
                    value='all',
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px', 'width': '100%'}
                )
            ], style={'marginRight': '10px', 'width': '50%'}),
            
            # 右侧总金额
            dbc.Col([
                html.Div([
                    html.Div("总金额:", style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}),
                    html.Div(id='branch-total-amount-display', children=total_amount, style={'color': '#00d4ff', 'fontSize': '16px', 'fontWeight': 'bold'})
                ], style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ], style={'marginRight': '10px', 'width': '50%'})
        ], style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        
        # 第三行：左侧选择框，右侧设备总数
        dbc.Row([
            # 左侧选择框
            dbc.Col([
                dcc.Dropdown(
                    id='branch-department-filter',
                    options=department_options,
                    value='all',
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px'}
                )
            ], style={'marginRight': '10px', 'width': '50%'}),
            
            # 右侧设备总数
            dbc.Col([
                html.Div([
                    html.Div("设备总数:", style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}),
                    html.Div(id='branch-total-count-display', children=total_count, style={'color': '#00ff88', 'fontSize': '16px', 'fontWeight': 'bold'})
                ], style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ], style={'marginRight': '10px', 'width': '50%'})
        ], style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        
            # 下方饼图部分
            html.Div([
                
                # 圆环图容器
                html.Div([
                    # 科室分布圆环图
                    html.Div([
                        dcc.Graph(
                            id='branch-asset-distribution-chart', 
                            figure=asset_pie_chart, 
                            config={'displayModeBar': False}, 
                            style={'height': '180px', 'width': '100%'}
                        ),
                        html.H4("科室分布", style={
                        "color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"
                    }),
                    ], style={'width': '50%'}),
                    
                    # 设备分类圆环图
                    html.Div([
                        dcc.Graph(
                            id='branch-asset-category-chart', 
                            figure=asset_pie_chart, 
                            config={'displayModeBar': False}, 
                            style={'height': '180px', 'width': '100%'}
                        ),
                        html.H4("设备分类", style={
                        "color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"
                    }),
                    ], style={'width': '50%'})
                ], style={'display': 'flex', 'flexDirection': 'row', 'justifyContent': 'space-between', 'alignItems': 'center'})
            ], className="dashboard-panel", style={  
                "margin": "2px 2px 2px 2px",
                # "background": "#101b41",
                "flex": "1 1 0",
                "minHeight": "0",
                "height": "100%",
                "display": "flex",
                "flexDirection": "column"
            })
        

    ], className="dashboard-panel",style={
        "backgroundColor": "#101b41",
        "padding": "5px",
        "borderRadius": "5px",
        "height": "99%"
        }
    
    
    )

# 创建设备运维面板（上排第2列）
def create_equipment_operation_panel():
    # 初始化图表
    inspection_fig = go.Figure(data=[go.Pie(
        labels=['完成', '未完成'],
        values=[0, 100],
        hole=0.7,
        marker_colors=['#00ff88', '#ff6b6b'],
        textinfo='none',
        direction='clockwise',
        rotation=0  # 修改为0，让绿色从12点开始
    )])
    
    maintenance_fig = go.Figure(data=[go.Pie(
        labels=['完成', '未完成'],
        values=[0, 100],
        hole=0.7,
        marker_colors=['#00ff88', '#ff6b6b'],
        textinfo='none',
        direction='clockwise',
        rotation=0  # 修改为0，让绿色从12点开始
    )])
    
    # 图表布局设置
    inspection_fig.update_layout(
        paper_bgcolor='rgba(0,0,0,0)',
        plot_bgcolor='rgba(0,0,0,0)',
        margin=dict(t=10, b=10, l=10, r=10),
        height=200,
        showlegend=False
    )
    
    maintenance_fig.update_layout(
        paper_bgcolor='rgba(0,0,0,0)',
        plot_bgcolor='rgba(0,0,0,0)',
        margin=dict(t=10, b=10, l=10, r=10),
        height=200,
        showlegend=False
    )
    
    return html.Div([
        # 第一行：标题
        html.H3(" | 设备运维", style={
            "color": "white",
            "fontSize": "18px",
            "marginBottom": "15px",
            "textAlign": "left",  # 修改为 left
            #"paddingTop": "1px" # 增加上边距
        }),
        
        # 第二行：选择框和巡检次数
        dbc.Row([
            # 左侧选择框
            dbc.Col([
                dcc.Dropdown(
                    id='branch-inspection-filter',
                    options=[
                        {'label': '一期', 'value': 'phase1'},
                        {'label': '二期', 'value': 'phase2'},
                       
                    ],
                    value='phase1',  # 默认选择一期
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px'}
                )
            ],  style={'marginRight': '10px', 'width': '40%'}),
            
            # 右侧巡检次数
            dbc.Col([
                html.Div([
                    html.Div("巡检次数", style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}),
                    html.Div(id="inspection-count-display", children="0",  style={'color': '#00ff88', 'fontSize': '16px', 'fontWeight': 'bold'})
                ],style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ],  style={'marginRight': '10px', 'width': '50%'})
        ],style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        
        # 第三行：下拉框和保养次数
        dbc.Row([
             # 左侧选择框（这个下拉框实际上不需要了，可以保留UI一致性）
            dbc.Col([
                dcc.Dropdown(
                    id='branch-maintain-filter',
                    options=[
                        {'label': '巡检', 'value': 'inspection'},
                        {'label': '保养', 'value': 'repair'},
                        
                    ],
                    value='repair',  # 默认选择保养
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px'}
                )
            ],  style={'marginRight': '10px', 'width': '40%'}),

            dbc.Col([
                html.Div([
                    html.Div("保养次数:", style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}),
                    html.Div(id="maintenance-count-display", children="0", style={'color': '#00ff88', 'fontSize': '16px', 'fontWeight': 'bold'})
                ], style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ],  style={'marginRight': '10px', 'width': '50%'})
        ], style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        
        # 第四行：饼图
        html.Div([
            
            # 圆环图容器
            html.Div([
                # 第一个图表 - 巡检完成率
                html.Div([
                    dcc.Graph(
                        id='inspection-completion-chart',
                        figure=inspection_fig, 
                        config={'displayModeBar': False},
                        style={'height': '180px', 'width': '100%'}
                    ),
                    html.H4("巡检完成率", style={
                        "color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"
                    }),
                    html.Div(id="inspection-completion-rate", children="0%", style={
                        "color": "#00ff88", "fontSize": "16px", "textAlign": "center", "fontWeight": "bold"
                    }),
                ], style={'width': '50%'}),
                
                # 第二个图表 - 保养完成率
                html.Div([
                    dcc.Graph(
                        id='maintenance-completion-chart',
                        figure=maintenance_fig, 
                        config={'displayModeBar': False},
                        style={'height': '180px', 'width': '100%'}
                    ),
                    html.H4("保养完成率", style={
                        "color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"
                    }),
                    html.Div(id="maintenance-completion-rate", children="0%", style={
                        "color": "#00ff88", "fontSize": "16px", "textAlign": "center", "fontWeight": "bold"
                    }),
                ], style={'width': '50%'})
            ], style={'display': 'flex', 'flexDirection': 'row', 'justifyContent': 'space-between', 'alignItems': 'center'})
        ], className="dashboard-panel", style={  
            "margin": "2px 2px 2px 2px",
            "flex": "1 1 0",
            "minHeight": "0",
        })
    ], className="dashboard-panel",style={
        "backgroundColor": "#101b41",
        "padding": "5px",
        "borderRadius": "5px",
        "height": "99%"
        }
    
    )


# 创建维修商面板布局
def create_repair_provider_panel_layout(selected_provider='all_repair_companies', total_repair_count=0, selected_repair_type='all_repair', repeat_repair_count=0):
    org_code = session.get('current_org_code', session.get('user_org_code'))
    # print(f"当前机构代码: {org_code}")
    org_name = None
    if org_code:
        organization = Organization.query.filter_by(org_code=org_code).first()
        # print(f"当前机构名称: {organization.short_name_c}")  # 打印机构名称以检查是否正确获取了机构名称
        if organization and organization.short_name_c:
            org_name = organization.short_name_c
    query = db.session.query(RepairRecord.repair_company).filter(RepairRecord.is_active == True)
    if org_name:
        query = query.filter(RepairRecord.org_shortname_c == org_name)
    companies = query.distinct().all()
    company_options = [{'label': c[0], 'value': c[0]} for c in companies if c[0]]
    company_options.insert(0, {'label': '全部维修商', 'value': 'all_repair_companies'})
    return html.Div([
        html.H3([
            " | ",
            html.A("维修商", href="/dash/repair", target="_blank", style={
               "color": "white",
                "fontSize": "18px",
                "bold": True,
                "margin": "0",
                "display": "inline-block",
                "textAlign": "left",  
                "cursor": "pointer"  # 鼠标悬停时显示手型
            })
        ], style={
            "color": "white",
            "fontSize": "18px",
            "marginBottom": "15px",
            "textAlign": "left"
        }),
        dbc.Row([
            dbc.Col([
                dcc.Dropdown(
                    id='provider-repaircompany-filter',
                    options=company_options,
                    value=selected_provider,
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px', 'width': '100%'}
                )
            ], style={'marginRight': '10px', 'width': '50%'}),
            dbc.Col([
                html.Div([
                    html.Div("维修重复率:", style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}),
                    html.Div(
                        f"{(repeat_repair_count / total_repair_count * 100):.2f}%" if total_repair_count else "0.00%",
                        style={'color': '#ff6b6b', 'fontSize': '16px', 'fontWeight': 'bold'}
                    )
                ], style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ], style={'marginRight': '10px', 'width': '50%'})
        ], style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        dbc.Row([
            dbc.Col([
                dcc.Dropdown(
                    id='repair-type-filter',
                    options=[
                        {'label': '全部维修', 'value': 'all_repair'},
                        {'label': '重复维修', 'value': 'repeat_repair'},
                    ],
                    value=selected_repair_type,
                    style={'backgroundColor': '#333', 'color': 'white', 'fontSize': '12px',}
                )
            ], style={'marginRight': '10px', 'width': '50%'}),
            dbc.Col([
                html.Div([
                    html.Div(
                        "重复维修次数:" if selected_repair_type == 'repeat_repair' else "维修次数:",
                        style={'color': 'white', 'fontSize': '16px', 'marginRight': '10px'}
                    ),
                    html.Div(
                        repeat_repair_count if selected_repair_type == 'repeat_repair' else total_repair_count,
                        style={'color': '#00ff88', 'fontSize': '16px', 'fontWeight': 'bold'}
                    )
                ], style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'center'})
            ], style={'marginRight': '10px', 'width': '50%'})
        ], style={'marginBottom': '5px', 'display': 'flex', 'flexDirection': 'row', 'flexWrap': 'nowrap'}),
        html.Div([
            html.Div([
                html.Div([
                    dcc.Graph(
                        id='provider-vendor-chart',
                        figure=go.Figure(),
                        config={'displayModeBar': False},
                        style={'height': '180px', 'width': '100%'}
                    ),
                    html.H4("维修商分布", style={"color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"}),
                ], style={'width': '50%'}),
                html.Div([
                    dcc.Graph(
                        id='provider-equipment-chart',
                        figure=go.Figure(),
                        config={'displayModeBar': False},
                        style={'height': '180px', 'width': '100%'}
                    ),
                    html.H4("设备类型分布", style={"color": "white", "fontSize": "14px", "textAlign": "center", "marginBottom": "2px"}),
                ], style={'width': '50%'})
            ], style={'display': 'flex', 'flexDirection': 'row', 'justifyContent': 'space-between', 'alignItems': 'center'})
        ], className="dashboard-panel", style={
            "margin": "2px 2px 2px 2px",
            "flex": "1 1 0",
            "minHeight": "0",
            "height": "100%",
            "display": "flex",
            "flexDirection": "column"
        })
    ], style={
        "backgroundColor": "#101b41",
        "padding": "5px",
        "borderRadius": "5px",
        "height": "99%"
    })
      
   




